package com.ykl.demo.comp.impl;

import com.ykl.base.comp.AbstractJpaEntityComp;
import com.ykl.base.jpa.ExecSqlComp;
import com.ykl.demo.comp.SpcRoomComp;
import com.ykl.demo.comp.conv.ValidateFailException;
import com.ykl.demo.entity.SpcRoom;
import com.ykl.demo.entity.SpcStation;
import com.ykl.demo.model.RoomExportCvsModel;
import com.ykl.demo.model.RoomImportResModel;
import com.ykl.demo.repo.SpcRoomRepo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SpcRoomCompImpl extends AbstractJpaEntityComp<SpcRoom> implements SpcRoomComp {

    private SpcRoomRepo mmRepo;

    @Autowired
    private ExecSqlComp mmSql;

    @Autowired
    private ConversionService mmServConvs;

    protected SpcRoomCompImpl(SpcRoomRepo repo) {
        super(repo);
        this.mmRepo = repo;
    }

    @Override
    public Page<SpcRoom> querySpcRoom(String roomId, String roomName, String roomNameContains, String stationNameStart,  Pageable pg) {

        return mmRepo.findByRoomIdAndRoomName(roomId, roomName, StringUtils.isBlank(roomNameContains)?".*":roomNameContains, StringUtils.isBlank(stationNameStart)?".*":("^"+stationNameStart), pg);
    }

    /**
     * 为导出查询.
     * @return 导出数据.
     */
    @Override
    public List<RoomExportCvsModel> query4Export(){
        //机房ID,机房名称,所属局站名称,机房地址,经度,纬度,机房等级,机房类型,投产时间
        String sql="SELECT r.room_id, r.address, r.china_name, r.class_id," +
                " s.china_name as station_name,  r.type_id, r.x, r.y, r.start_use_date" +
                " FROM ykl.spc_room r left join ykl.spc_station s on r.station_id = s.station_id";

        return mmSql.exec(sql, RoomExportCvsModel.class);
    }

    @Override
    public RoomImportResModel importRoom(String filename, int rowNo, SpcStation station, RoomImportResModel origin) {
        try {
            SpcRoom room = mmServConvs.convert(origin, SpcRoom.class);
            save(room);
        }catch (Throwable ex){
            while(!(ex instanceof  ValidateFailException)){
                ex = ex.getCause();
                if(ex==null){
                    break;
                }
            }
            if(ex!=null) {
                origin.setReason(ex.getLocalizedMessage());
            }else{
                origin.setReason("无法识别的错误");
            }
        }
        return origin;
    }

    @Override
    public List<SpcRoom> findByStationId(String stationId) {
        return mmRepo.findByStationId(stationId);
    }
}
